package com.l.im.service.handler;


import com.l.im.common.auth.JwtSecret;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: LIM
 * @description: auth校验
 * @author: Alex Wu
 * @createDate: 2025-04-15 11:12
 **/
@Slf4j
public class JwtAuthenticationHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 检查是否是 HTTP 握手请求
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;

            // 从请求头获取 Authorization 字段
            String authorizationHeader = request.headers().get(HttpHeaders.Names.AUTHORIZATION);

            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                String token = authorizationHeader.substring(7); // 去除 "Bearer " 前缀

                try {
                    // 校验 JWT 是否有效
                    boolean tokenExpired = JwtSecret.isTokenExpired(token);

                    log.info("JWT 校验通过 ", tokenExpired);

                    // JWT 校验通过，将标志设置到 Channel 属性中
                    ctx.channel().attr(AttributeKey.valueOf("isAuthenticated")).set(tokenExpired);

                    // 继续处理请求
                    super.channelRead(ctx, msg);
                } catch (Exception e) {
                    // JWT 校验失败，拒绝连接
                    ctx.channel().attr(AttributeKey.valueOf("isAuthenticated")).set(false);
                    ctx.close();  // 关闭连接
                }
            } else {
                // 如果没有 Authorization 头部，拒绝连接
                ctx.channel().attr(AttributeKey.valueOf("isAuthenticated")).set(false);
                ctx.close(); // 关闭连接
            }
        } else {
            // 如果不是 HTTP 请求，继续传递
            super.channelRead(ctx, msg);
        }
    }
}

